package com.zyx.shiro.service.impl;

import com.zyx.shiro.entity.Perms;
import com.zyx.shiro.entity.User;
import com.zyx.shiro.mapper.UserMapper;
import com.zyx.shiro.service.IUserService;
import com.zyx.shiro.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zyx
 * @since 2023/9/9 01:06
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 用户注册
     */
    public void register(User user) {
        // 处理业务调用 mapper
        // 1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        // 2.将随机盐保存到数据
        user.setSalt(salt);
        // 3.明文密码进行md5 + salt + hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        userMapper.save(user);
    }

    @Override
    public User findByUserName(String principal) {
        return userMapper.findByUserName(principal);
    }

    @Override
    public User findRolesByUserName(String username) {
        return userMapper.findRolesByUserName(username);
    }

    @Override
    public List<Perms> findPermsByRoleId(String id) {
        return userMapper.findPermsByRoleId(id);
    }

    @Override
    public User findRolesAndPermsByUserName(String username) {
        return userMapper.findRolesAndPermsByUserName(username);
    }


}
